package com.andy.permission.utils

import android.app.Activity
import com.andy.permission.interceptor.PermissionInterceptor
import com.hjq.permissions.XXPermissions

/**
 * Author:Andy
 * Date:2023/3/23 11:40
 * Description:PermissionUtils
 */
object PermissionUtils {

    /**
     * 判断是否有此权限
     */
    fun isGranted(activity: Activity, permission: String): Boolean {
        return XXPermissions.isGranted(activity, permission)
    }

    /**
     * 判断是否有此权限
     */
    fun isGranted(activity: Activity, permissions: Array<String>): Boolean {
        return XXPermissions.isGranted(activity, permissions)
    }

    /**
     * 判断是否有此权限
     */
    fun checkAndRequestPermission(activity: Activity, permission: String, callBack: ((isGranted: Boolean, isNotAskAgain: Boolean) -> Unit)? = null) {
        if (isGranted(activity, permission)) {
            callBack?.invoke(true, false)
        } else {
            XXPermissions.with(activity)
                .permission(permission)
                .interceptor(PermissionInterceptor {
                    callBack?.invoke(false, it)
                })
                .request { permissions, allGranted ->
                    if (allGranted) {
                        callBack?.invoke(true, false)
                    } else {
                        callBack?.invoke(false, false)
                    }
                }
        }
    }

    /**
     * 判断是否有这些权限
     */
    fun checkAndRequestPermissions(activity: Activity, permissions: Array<String>, callBack: ((isGranted: Boolean, isNotAskAgain: Boolean) -> Unit)? = null) {
        if (isGranted(activity, permissions)) {
            callBack?.invoke(true, false)
        } else {
            XXPermissions.with(activity)
                .permission(permissions)
                .interceptor(PermissionInterceptor {
                    callBack?.invoke(false, it)
                })
                .request { permissions, allGranted ->
                    if (allGranted) {
                        callBack?.invoke(true, false)
                    } else {
                        callBack?.invoke(false, false)
                    }
                }
        }
    }

    /**
     * 跳转到设置页面开启权限
     */
    fun jumpAndStartPermission(activity: Activity, permission: String) {
        XXPermissions.startPermissionActivity(activity, permission)
    }

    /**
     * 跳转到设置页面开启权限
     */
    fun jumpAndStartPermissions(activity: Activity, permissions: Array<String>) {
        XXPermissions.startPermissionActivity(activity, permissions)
    }
}